﻿using System;
using System.Diagnostics;
using System.Text;

namespace H.Logger.Logs
{
    /// <summary>
    /// 描述一个日志的所有信息
    /// </summary>
    internal class HLogInfo
    {
        /// <summary>
        /// 日志产生时间
        /// </summary>
        public DateTime DateTime;

        /// <summary>
        /// 日志等级
        /// </summary>
        public string Level;

        /// <summary>
        /// 打印日志的类名
        /// </summary>
        public string ClassName;

        /// <summary>
        /// 日志内容
        /// </summary>
        public string Message;

        /// <summary>
        /// 日志附带的异常信息
        /// </summary>
        public Exception Exception;

        /// <summary>
        /// 日志附带的堆栈信息
        /// </summary>
        public StackTrace StackTrace;

        /// <summary>
        /// 递归打印一个异常
        /// </summary>
        /// <param name="sb">异常文本输出的位置</param>
        /// <param name="exception">异常对象</param>
        public static void PrintException(StringBuilder sb, Exception exception)
        {
            sb.AppendFormat("{0}({1}:{2})\r\n{3}\r\n", exception.Message, exception.Source, exception.TargetSite, exception.StackTrace);
            if (exception.InnerException != null)
            {
                sb.AppendLine("-----------------------------内部异常------------------------------");
                PrintException(sb, exception.InnerException);
            }
        }

        /// <summary>
        /// 将日志显示为文本信息
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0} [{1,-5}] {2,10}| {3}\r\n", DateTime, Level, ClassName, Message);
            if (Exception != null)
            {
                PrintException(sb, Exception);
            }

            if (StackTrace != null)
            {
                sb.AppendLine(StackTrace.ToString());
            }

            return sb.ToString();
        }
    }
}
